<template>
  <view class="coupon-center">
    <!-- <view class="header"></view> -->

    <view class="coupon-list">
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      <view v-else-if="coupons.length === 0" class="empty">
        <text>暂无可用优惠券</text>
      </view>
      <view v-else>
        <CouponItem
          v-for="(coupon, index) in coupons"
          :key="index"
          :coupon-data="coupon"
          :enable-share="false"
          @get="handleGetCoupon"
        />
      </view>
    </view>

    <!-- 分享进入时显示的特定优惠券 -->
    <view v-if="sharedCoupon" class="shared-coupon-container">
      <view class="mask" @click="closeSharedCoupon"></view>
      <view class="shared-coupon">
        <view class="close-btn" @click="closeSharedCoupon">×</view>
        <text class="share-title">好友分享的优惠券</text>
        <CouponItem
          :coupon-data="sharedCoupon"
          :enable-share="false"
          @get="handleGetCoupon"
        />
        <button class="more-btn" @click="closeSharedCoupon">
          查看更多优惠券
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import CouponItem from "@/components/coupon-item/coupon-item.vue";
import { store } from "@/uni_modules/uni-id-pages/common/store.js";

export default {
  components: {
    CouponItem,
  },
  data() {
    return {
      loading: true,
      coupons: [],
      sharedCoupon: null,
      couponId: "", // 从分享链接获取的优惠券ID
    };
  },
  mounted() {
    uni.hideHomeButton();
  },
  onLoad(options) {
    // 监听登录成功事件
    uni.$on("uni-id-pages-login-success", () => {
      // 构建重定向URL，保留原始参数
      const redirectUrl = this.couponId
        ? `/pages/coupon/center?id=${this.couponId}`
        : "/pages/coupon/center";

      uni.redirectTo({
        url: redirectUrl,
        success: () => {
          // 重定向成功后刷新数据
          this.loadCoupons();
          if (this.couponId) {
            this.getSharedCouponInfo(this.couponId);
          }
        },
      });
    });

    // 获取分享链接中的优惠券ID
    if (options.id) {
      this.couponId = options.id;
      this.getSharedCouponInfo(options.id);
    }

    // 加载所有优惠券
    this.loadCoupons();
  },
  // 获取当前用户信息
  computed: {
    currentUser() {
      return store.userInfo;
    },
  },
  methods: {
    // 加载所有优惠券
    async loadCoupons() {
      this.loading = true;
      try {
        const userInfo = this.currentUser;
        if (!userInfo || !userInfo._id) {
          uni.showToast({
            title: "请先登录",
            icon: "none",
          });
          this.loading = false;
          return;
        }

        const couponManager = uniCloud.importObject("coupon-manager");
        const result = await couponManager.getUserCoupons(userInfo._id);

        // console.log("loadCoupons result: ", result);

        if (result.code === 200) {
          this.coupons = result.data.map((item) => ({
            _id: item._id,
            user_id: item.user_id || "", // 优惠券所属的商户ID
            name: item.coupon_info[0].name || "优惠券",
            discount: item.coupon_info[0].discount || 0,
            validity: item.coupon_info[0].validity || "暂无日期",
            customImage: item.customImage || "/static/default-avatar.png",
            status: item.status || 0,
            receive_date: this.formatDate(item.receive_date),
          }));
        } else {
          throw new Error(result.message);
        }
      } catch (error) {
        console.error("加载优惠券失败", error);
        uni.showToast({
          title: "加载优惠券失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    // 添加日期格式化方法
    formatDate(timestamp) {
      if (!timestamp) return "暂无日期";
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")}`;
    },

    // 处理领取优惠券
    async handleGetCoupon(coupon) {
      try {
        const userInfo = this.currentUser;
        if (!userInfo || !userInfo._id) {
          uni.showToast({
            title: "请先登录",
            icon: "none",
          });
          return;
        }

        const couponManager = uniCloud.importObject("coupon-manager");

        // 使用云对象检查是否已领取
        const checkResult = await couponManager.checkCouponReceived({
          coupon_id: coupon._id,
          user_id: userInfo._id,
        });

        if (checkResult.code === 200 && checkResult.data.received) {
          uni.showToast({
            title: "您已领取过该优惠券",
            icon: "none",
          });
          return;
        }

        // 创建领取记录
        const result = await couponManager.receiveCoupon({
          coupon_id: coupon._id,
          user_id: userInfo._id,
          status: 0, // 已领取
        });

        if (result.id) {
          uni.showToast({
            title: "领取成功",
            icon: "success",
          });
        }
      } catch (error) {
        console.error("领取优惠券失败:", error);
        uni.showToast({
          title: "领取失败，请重试",
          icon: "none",
        });
      }
    },
    // 获取分享的优惠券信息
    async getSharedCouponInfo(couponId) {
      try {
        const db = uniCloud.database();
        const { result } = await db
          .collection("coupons")
          .where({ _id: couponId })
          .get();

        // console.log("couponId： ", couponId)
        // console.log("getSharedCouponInfo result: ", result)

        if (result.data && result.data.length > 0) {
          this.sharedCoupon = result.data[0];
        }
      } catch (error) {
        console.error("获取优惠券信息失败:", error);
        uni.showToast({
          title: "获取优惠券信息失败",
          icon: "none",
        });
      }
    },

    // 关闭分享优惠券弹窗
    async closeSharedCoupon() {
      if (this.sharedCoupon) {
        try {
          const userInfo = this.currentUser;
          if (!userInfo || !userInfo._id) {
            uni.showToast({
              title: "请先登录",
              icon: "none",
            });
            return;
          }

          const couponManager = uniCloud.importObject("coupon-manager");
          const result = await couponManager.receiveCoupon({
            coupon_id: this.sharedCoupon._id,
            user_id: userInfo._id,
            validity: this.sharedCoupon.validity,
          });

          if (result.code === 200) {
            uni.showToast({
              title: result.message,
              icon: "success",
            });
          } else {
            uni.showToast({
              title: result.message,
              icon: "none",
            });
          }
        } catch (error) {
          console.error("处理优惠券失败:", error);
          uni.showToast({
            title: "操作失败，请重试",
            icon: "none",
          });
        }
      }

      // 关闭弹窗
      this.sharedCoupon = null;
    },
  },
  // 定义分享行为
  onShareAppMessage() {
    return {
      title: "精选优惠券，等你来领！",
      path: "/pages/coupon/center",
      imageUrl: "/static/logo.png",
    };
  },
};
</script>

<style>
.coupon-center {
  padding: 40rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 50rpx;
  text-align: center;
  padding: 20rpx 0;
}

.title {
  font-size: 42rpx;
  font-weight: 600;
  color: #2c3e50;
  display: block;
  margin-bottom: 16rpx;
  letter-spacing: 2rpx;
}

.subtitle {
  font-size: 26rpx;
  color: #6c757d;
  letter-spacing: 1rpx;
}

.coupon-list {
  margin-top: 30rpx;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 40rpx;
}

.coupon-list > view {
  transition: all 0.3s ease;
}

.coupon-list > view:last-child {
  margin-bottom: 0;
}

::v-deep .coupon-item {
  background: #fff9f9;
  border-radius: 16rpx;
  height: 350rpx;
  margin: 10rpx 0 20rpx;
}

::v-deep .coupon-left {
  background: linear-gradient(135deg, #ff4757 0%, #ff6b81 100%);
  width: 200rpx;
}

::v-deep .coupon-right {
  padding: 30rpx;
}

::v-deep .coupon-name {
  font-size: 32rpx;
  font-weight: bold;
}

::v-deep .get-btn {
  background-color: #ff4757;
  color: #ffffff;
  height: 60rpx !important;
  line-height: 60rpx !important;
}

.loading,
.empty {
  text-align: center;
  padding: 60rpx 0;
  color: #6c757d;
  font-size: 28rpx;
}

.shared-coupon-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(4px);
}

.shared-coupon {
  position: relative;
  width: 85%;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 50rpx 30rpx;
  z-index: 1000;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.close-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  font-size: 44rpx;
  color: #6c757d;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.close-btn:active {
  transform: scale(0.9);
}

.share-title {
  text-align: center;
  font-size: 36rpx;
  font-weight: 600;
  margin-bottom: 40rpx;
  display: block;
  color: #2c3e50;
}

.more-btn {
  margin-top: 40rpx;
  background-color: #ff6b6b;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 30rpx;
  padding: 20rpx 0;
  transition: all 0.3s ease;
}

.more-btn:active {
  transform: scale(0.98);
  background-color: #ff5252;
}
</style>
